<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >

      <div class="title-container">
        <h3 class="title">
          {{ $t('login.title') }}
        </h3>
        <lang-select class="set-language" />
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          :placeholder="$t('login.username')"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            :placeholder="$t('login.password')"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:20px;" @click="handleLogin">
        {{ $t('login.logIn') }}
      </el-button>

      <!--      <div style="position:relative">-->
      <!--        <el-button class="forget-password-button" type="primary" style="float:right;" @click="handleForgetPassword">-->
      <!--          {{ $t('login.forgetPassword') }}-->
      <!--        </el-button>-->
      <!--      </div>-->

      <el-button class="forget-password-button" type="primary" style="float:right;" @click="showDialog=true">
        {{ $t('login.forgetPassword') }}
      </el-button>
    </el-form>

    <el-dialog class="forget-dialog" :title="$t('login.forgetPassword')" :visible.sync="showDialog">
      <el-form
        ref="forgetForm"
        :model="forgetForm"
        :rules="forgetRules"
        class="forget-form"
        autocomplete="on"
        label-position="left"
      >

        <div class="title-container">
          <h3
            style="font-size: 26px;
      color: lightgray;
      margin: 0 auto 10px auto;
      text-align: center;
      font-weight: bold;"
          >
            {{ $t('forgetPassword.title') }}
          </h3>
          <lang-select class="set-language" />
        </div>

        <el-form-item prop="account">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="account"
            v-model="forgetForm.account"
            :placeholder="$t('forgetPassword.account')"
            name="account"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>

        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="forgetForm.password"
              :type="passwordType"
              :placeholder="$t('forgetPassword.password')"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleConfirm"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>

        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="confirmPassword">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="forgetForm.confirmPassword"
              :type="passwordType"
              :placeholder="$t('forgetPassword.confirmPassword')"
              name="confirmPassword"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleConfirm"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>

        <el-form-item prop="verify" style="width: 65%;float: left;">
          <span class="svg-container">
            <svg-icon icon-class="message" />
          </span>
          <el-input
            ref="username"
            v-model="forgetForm.verify"
            :placeholder="$t('forgetPassword.verify')"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>
        <el-button
          id="get-verify-btn"
          style="color: whitesmoke;width: 35%;height: 50px;background: transparent"
          @click="sendVerify"
        >
          {{ $t('forgetPassword.sendVerify') }}
        </el-button>

        <div style="position:relative">
          <el-button
            :loading="loading"
            type="primary"
            style="width: 100%;margin-bottom: 25px;"
            @click.native.prevent="handleConfirm"
          >
            {{ $t('forgetPassword.confirm') }}
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import LangSelect from '@/components/LangSelect'
import { validEmail } from '@/utils/validate'
import { resetPassword, sendForgetVerify } from '@/api/user'

export default {
  name: 'Login',
  components: { LangSelect },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('Login account can not be null'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('Password can not be null'))
      } else {
        callback()
      }
    }
    const validateForgetUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please enter the correct email account'))
      } else {
        if (!validEmail(value)) {
          callback(new Error('There is an error, please enter your email account'))
        } else {
          callback()
        }
      }
    }
    const validatePassword1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please enter a new password'))
      } else {
        if (this.forgetForm.confirmPassword !== '') {
          this.$refs.forgetForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePassword2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please enter the password again'))
      } else if (value !== this.forgetForm.password) {
        callback(new Error('The passwords entered twice do not match'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        // username: 'shjin@icloud.com',
        // username: '495883522146757056',
        // username: '788395100998',
        // username: '17573410175',
        username: '14811420370',
        password: '123456'
      },
      loginRules: {
        username: [{ required: true, validateUsername, trigger: 'blur' }],
        password: [{ required: true, validatePassword, trigger: 'blur' }]
      },
      forgetForm: {
        account: '',
        password: '',
        confirmPassword: '',
        verify: ''
      },
      forgetRules: {
        account: [{ required: true, trigger: 'blur', validator: validateForgetUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword1 }],
        confirmPassword: [{ required: true, trigger: 'blur', validator: validatePassword2 }],
        verify: [{ required: true, message: 'verification code must be filled' }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取验证码
    sendVerify() {
      if (validEmail(this.forgetForm.account)) {
        // 发送请求获取验证码，发送成功给出提出
        sendForgetVerify(this.forgetForm.account).then(response => {
          const data = response.data
          if (data === 1) {
            // this.$message.success('The verification code has been sent successfully, please check your email!')
            this.$message({
              type: 'success',
              message: 'The verification code has been sent successfully, please check your email!',
              duration: 1000
            })
          }
        })
        let nums = 60
        const verify = document.getElementById('get-verify-btn')
        verify.disabled = 'disabled'
        verify.innerText = nums + '秒后重新获取'
        // 一秒执行一次
        // eslint-disable-next-line prefer-const
        let clock = setInterval(() => {
          nums--
          if (nums > 0) {
            verify.innerText = nums + '秒后重新获取'
          } else {
            // 清除 js 定时器
            clearInterval(clock)
            verify.disabled = false
            verify.innerText = '获取验证码'
            // 重置时间
            nums = 60
          }
        }, 1000)
      } else {
        this.$message({
          message: 'Please enter your email account!',
          type: 'error',
          duration: 3000
        })
      }
    },
    handleConfirm() {
      this.$refs.forgetForm.validate(valid => {
        if (valid) {
          resetPassword(this.forgetForm).then(response => {
            const data = response.data
            if (data >= 1) {
              this.$message({
                message: 'Password changed successfully, please log in again!',
                type: 'success',
                duration: 3000
              })
              this.loginForm.username = this.forgetForm.account
              this.loginForm.password = this.forgetForm.password
              this.showDialog = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0;
      -webkit-appearance: none;
      border-radius: 0;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}

.forget-dialog .el-dialog__body {
  background-color: #2d3a4b;
}

.forget-dialog .el-dialog__header {
  background-color: #2d3a4b;
}

.forget-dialog .el-dialog__title {
  color: #f4f4f5;
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.forget-form {
  position: relative;
  width: 520px;
  max-width: 100%;
  //padding: 10px 35px 0;
  margin: 0 auto;
  overflow: hidden;
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0 auto 40px auto;
      text-align: center;
      font-weight: bold;
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0;
      cursor: pointer;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
